//
//  PhotoBrowserViewController.swift
//  LVWeibo
//
//  Created by lv on 15/7/4.
//  Copyright © 2015年 lv. All rights reserved.
//

import UIKit
import FFAutoLayout
import SVProgressHUD

// 照片浏览器可重用ID
private let WBPhotoBrowserCellIdentifier = "WBPhotoBrowserCellIdentifier"
class PhotoBrowserViewController: UIViewController {

    // 当前图片索引
    private var photoIndex = 0
    
    init(urls: [NSURL],photoIndex: Int)
    {
        // 先初始化本类的属性
        imageURLs = urls
        currentIndex = photoIndex
        
        // 再在调用系统提供的父类构造函数
        super.init(nibName: nil, bundle: nil)
    }
    override func loadView() {
        
        // 初始化控制器View
        view = UIView(frame: UIScreen.mainScreen().bounds)
        view.backgroundColor = UIColor.blackColor()
        
        // 添加子控件
        view.addSubview(photoBrowserView)
        view.addSubview(saveBtn)
        view.addSubview(originPicBtn)
        view.addSubview(closeBtn)
        view.addSubview(photoCountLabel)

        
        // 自动布局
        photoBrowserView.ff_Fill(view)
        saveBtn.ff_AlignInner(ff_AlignType.BottomLeft, referView: view, size: CGSize(width: 60, height: 30), offset: CGPoint(x: 12, y: -12))
        originPicBtn.ff_AlignHorizontal(ff_AlignType.CenterRight, referView: saveBtn, size: CGSize(width: 60, height: 30), offset: CGPoint(x: 12, y: 0))
        closeBtn.ff_AlignHorizontal(ff_AlignType.CenterRight, referView: originPicBtn, size: CGSize(width: 60, height: 30), offset: CGPoint(x: 12, y: 0))
        photoCountLabel.ff_AlignVertical(ff_AlignType.TopCenter, referView: view, size: CGSize(width: 100, height: 30), offset: CGPoint(x: 0, y: 50))
        photoCountLabel.backgroundColor = UIColor(white: 1.0, alpha: 0.8)
        
        // 按钮点击事件
        saveBtn.addTarget(self, action: "saveBtnClick", forControlEvents: UIControlEvents.TouchUpInside)
        closeBtn.addTarget(self, action: "closeBtnClick", forControlEvents: UIControlEvents.TouchUpInside)
        originPicBtn.addTarget(self, action: "originBtnClick", forControlEvents: UIControlEvents.TouchUpInside)
    }
     //MARK:- 完成子视图 view OK collectionView OK
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        
        // 准备collectionView
        prepareCollectionView()
        
        // 显示用户选中的照片
        let indexPath = NSIndexPath(forItem: currentIndex, inSection: 0)
        photoBrowserView.scrollToItemAtIndexPath(indexPath, atScrollPosition: UICollectionViewScrollPosition.CenteredHorizontally, animated: false)
    }
    
    //MARK:- 准备collectionView
    private func prepareCollectionView() {
        layout.itemSize = photoBrowserView.bounds.size
        layout.minimumInteritemSpacing = 50
        layout.minimumLineSpacing = 0
        layout.scrollDirection = UICollectionViewScrollDirection.Horizontal
        
        photoBrowserView.pagingEnabled = true
        
        // 注册cell
        photoBrowserView.registerClass(PhotoBrowserCell.self, forCellWithReuseIdentifier: WBPhotoBrowserCellIdentifier)
        // 设置数据源
        photoBrowserView.dataSource = self
    }
    
    //MARK:- 按钮点击事件实现方法
    ///  保存
    func saveBtnClick() {
        // 获取要保存图片的indexPath
        let indexPath = photoBrowserView.indexPathsForVisibleItems().last!
        let cell = photoBrowserView.cellForItemAtIndexPath(indexPath) as! PhotoBrowserCell
        let image = cell.imageView.image!
        
        UIImageWriteToSavedPhotosAlbum(image, self, "image:didFinishSavingWithError:contextInfo:", nil)
    }
    //  - (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo;
    func image(image: UIImage,didFinishSavingWithError error:NSError?,contextInfo:AnyObject) {
        if error != nil {
            SVProgressHUD.showErrorWithStatus("保存出错")
        }else {
            SVProgressHUD.showSuccessWithStatus("保存成功")
        }
    }
    
    ///  原图
    func originBtnClick() {
        
    }
    ///  关闭
    func closeBtnClick() {
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    //MARK:- viewDidLoad
    override func viewDidLoad() {
        super.viewDidLoad()
        print(imageURLs)
        photoCountLabel.text = "\(photoIndex + 1)"
    }
    
    /// 图片数组
    private var imageURLs: [NSURL]
    /// 用户选中照片索引
    private var currentIndex: Int
    /// 懒加载collectionView
    /// 定义collectionView的布局
    lazy private var layout = UICollectionViewFlowLayout()
    lazy private var photoBrowserView: UICollectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: self.layout)
    /// 懒加载按钮
    lazy private var saveBtn: UIButton = UIButton(btnTitle: "保 存", titleColor: UIColor.whiteColor(), fontSize: 13)
    lazy private var originPicBtn: UIButton = UIButton(btnTitle: "原 图", titleColor: UIColor.whiteColor(), fontSize: 13)
    lazy private var closeBtn: UIButton = UIButton(btnTitle: "关 闭", titleColor: UIColor.whiteColor(), fontSize: 13)
    lazy private var photoCountLabel: UILabel = UILabel(textColor: UIColor.whiteColor(), fonSize: 13, layoutWidth: UIScreen.mainScreen().bounds.width, mutiLines: true)
}

//MARK:- CollectionView数据源方法
extension PhotoBrowserViewController: UICollectionViewDataSource,PhotoBrowserCellDelegate,UICollectionViewDelegate {
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return imageURLs.count
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(WBPhotoBrowserCellIdentifier, forIndexPath: indexPath) as! PhotoBrowserCell
        cell.imageURL = imageURLs[indexPath.item]
        
        // 设置cell的代理
        cell.photoDelegate = self
        return cell
    }
    func collectionView(collectionView: UICollectionView, didEndDisplayingCell cell: UICollectionViewCell, forItemAtIndexPath indexPath: NSIndexPath) {
        // 获取当前显示cell的indexPath
        photoIndex = photoBrowserView.indexPathsForVisibleItems().last!.item
    }
    
    
    //MARK:- PhotoBrowserCellDelegate
    func photoViewerCellDidTapImage() {
        // 关闭界面
        closeBtnClick()
    }
}